package cn.iocoder.yudao.module.study.message.handle.impl;

import cn.hutool.core.util.URLUtil;
import cn.iocoder.yudao.module.study.message.handle.ISendMsgService;
import cn.iocoder.yudao.module.study.message.vo.MsgVO;
import lombok.extern.slf4j.Slf4j;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.study.enums.ErrorCodeConstants.MSG_REWRITE_OAUTH_URL;
/**
 * @Author cjc
 * @Date 2024/3/19 16:33
 * @Description: 发送消息抽象实现类
 * @Version 1.0
 */
@Slf4j
public abstract class AbstractSendMsgImpl implements ISendMsgService {

    protected static final  String DING_TALK_SEND_MSG_URL = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2";
    protected static final  String DING_TALK_OAUTH2_URL = "/els/account/thirdLogin/render/%s/mobile/dingtalk_account";
    protected static final  String FEI_SHU_SEND_MSG_URL = "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=union_id";
    protected static final  String FEI_SHU_OAUTH2_URL = "/els/account/thirdLogin/render/%s/mobile/feishu";
    protected static final  String WECHAT_EP_SEND_MSG_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send";
    protected static final  String WECHAT_EP_OAUTH2_URL = "/els/account/thirdLogin/render/%s/mobile/wechat_enterprise_web";
    protected static final  String WECHAT_MP_SEND_MSG_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send";
    protected static final  String WECHAT_MP_OAUTH2_URL = "/els/account/thirdLogin/render/%s/mobile/wechat_mp";

    /**
     *
     * 执行发送消息操作
     *
     * @param msgVO
     */
    public abstract void doSendMsg(MsgVO msgVO);


    @Override
    public void sendMsg(MsgVO msgVO) {
        // 发送消息
        doSendMsg(msgVO);
        try {
            //记录系统日志
            log.info("插入sql...记录一条消息日志");
        } catch (Exception e) {
            log.error("AbstractSendMsgImpl_log failed:",e);
        }
    }


    /**
     * 构建url
     * @param urlParam
     * @param busAccount
     * @return
     */
    protected String getUrl(String urlParam,String busAccount) {
        String routeUri = URLUtil.encodeAll(urlParam);
        return   getServiceBuilder()
                .append(String.format(getOauthUrl(),busAccount))
                .append("?routeUri=")
                .append(routeUri).toString();
    }

    /**
     * 获取url参数
     * @return
     */
    protected StringBuilder getServiceBuilder(){
        return new StringBuilder("");
    }

    protected String getOauthUrl(){
        // 要用到就重写
        throw exception(MSG_REWRITE_OAUTH_URL);
    }

}
